//
// Created by A on 2022/10/14.
//

#include "include/util.h"


struct timespec to_timespec(time_t ns);
struct timespec to_timespec(time_t ns) {
    time_t sec = ns / 1000000000;
    struct timespec ret = {
            .tv_sec=sec,
            .tv_nsec = ns - (sec * 1000000000)
    };
    return ret;
}

time_t to_ns_time(const struct timespec *timespec) {
    return timespec->tv_sec * 1000000000 + timespec->tv_nsec;
}

struct timespec diff_from_now(time_t ms) {
    struct timespec start_tm;
    clock_gettime(CLOCK_REALTIME, &start_tm);
    return to_timespec(to_ns_time(&start_tm) + ms * 1000000);
}

bool cas_int(volatile int *addr, int oldVal, int newVal) {
    int ret;
    __asm__ __volatile__(
            "lock;cmpxchg %2,%3"
            :"=a"(ret), "=m"(*addr)
            :"r" (newVal), "m" (*addr), "0" (oldVal)
            :"cc"
            );
    return ret == oldVal;
}


